import { computed, ref } from 'vue';
import { GlobalDataProps } from '@/store';
import { useRoute } from 'vue-router';
import { useStore } from 'vuex';
import useSaveWork from './useSaveWork';
import { takeScreenshotAndUpload } from '../helper';

function usePublishWork() {
    // 数据准备
    const { saveWork } = useSaveWork();
    const route = useRoute();
    const currentWorkId = route.params.id;
    const store = useStore<GlobalDataProps>();
    const channels = computed(() => store.state.editor.channels);
    const isPublishing = ref(false);

    const publishWork = async (el: HTMLElement) => {
        try {
            // 1. 快照上传
            const resp = await takeScreenshotAndUpload(el);
            if (resp) {
                // 2. 更新page coverImg
                store.commit('updatePage', {
                    key: 'coverImg',
                    value: resp.data.urls[0],
                    isRoot: true,
                });
                // 3. 保存work
                await saveWork();
                // 4. 发布work
                await store.dispatch('publishWork', { urlParams: { id: currentWorkId } });
                // 5. 查询channels list
                await store.dispatch('fetchChannels', { urlParams: { id: currentWorkId } });
                // 6. 如果没有channels list，创建一个新channel
                if (channels.value.length === 0) {
                    await store.dispatch('createChannel', {
                        data: { name: '默认', workId: parseInt(currentWorkId as string) },
                    });
                }
            }
        } catch (e) {
            console.error(e);
        } finally {
            isPublishing.value = false;
        }
    };
    return {
        publishWork,
        isPublishing,
    };
}

export default usePublishWork;
